iT邦幫忙

2023 iThome 鐵人賽

DAY 30
0

上一篇已經把搜尋的功能完成了,但是搜尋的畫面看起來有點單調,所以這篇文章會使用 Lottie 動畫增加 App 的視覺效果。

Lottie 是什麼?

Lottie 是 Airbnb 開發的一個動畫函式庫,可以讓我們使用 JSON 檔案來播放動畫,而且支援 iOS、Android、React Native、Web、Windows、macOS、Unity、Lottie Viewer 等平台。

使用 Lottie

那麼在 React Native 中要如何使用 Lottie 呢?我們可以使用 lottie-react-native 這個套件來使用 Lottie。

安裝套件

首先先安裝套件:

npx expo install lottie-react-native

下載動畫檔案

接著到 LottieFiles 搜尋自己喜歡的動畫,這裡有非常多的動畫可以使用,都是許多設計師分享的,而且都是免費的,可以直接下載使用。

我這裡選擇這一個動畫,點擊右上角的 Download 按鈕,選擇 Lottie JSON,然後就會下載一個 JSON 檔案。檔案可以放在自己喜歡的位置,這裡我放在 assets 資料夾中。

設定動畫

接下來就在 Search.tsx 中設定動畫,首先先匯入 LottieView

import { FC } from 'react'
import {
  SafeAreaView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
  useWindowDimensions
} from 'react-native'
import { StackNavigationProp } from '@react-navigation/stack'
import LottieView from 'lottie-react-native'
import useStore from '../store'

type TabNavigatorParams = {
  Home: undefined
  Search: undefined
}

type SearchProps = {
  navigation: StackNavigationProp<TabNavigatorParams, 'Search'>
}

const Search: FC<SearchProps> = ({ navigation }) => {
  const { searchCity, setSearchCity, fetchLatLngByCity } = useStore()

  const handleCityPress = () => {
    if (searchCity) {
      fetchLatLngByCity()
      navigation.navigate('Home')
    }

    navigation.navigate('Home')
  }

  const buttonText = searchCity ? 'Search' : 'Current Location'
  const windowWidth = useWindowDimensions().width
  const itemWidth = windowWidth / 2

  return (
    <SafeAreaView className='flex-1 bg-blue-500'>
      <View className='items-center gap-y-4 mt-2'>
        <TextInput
          className='w-11/12 border border-gray-300 bg-white rounded-lg px-1 h-12'
          onChangeText={setSearchCity}
          value={searchCity}
          placeholder='Search for a city...'
        />
        <TouchableOpacity
          className='w-2/3 bg-lime-500 rounded-full p-4'
          onPress={handleCityPress}
        >
          <Text className='text-center font-semibold'>{buttonText}</Text>
        </TouchableOpacity>
      </View>
      <View className='items-center mt-16'>
        <LottieView
          loop
          autoPlay
          source={require('../assets/location.json')}
          style={{
            width: itemWidth,
            height: itemWidth
          }}
        />
      </View>
    </SafeAreaView>
  )
}

這裡要注意的是,source 的值要填入剛剛下載的 JSON 檔案,這裡我放在 assets 資料夾中,所以要使用 require 來匯入。

然後就可以在模擬器中看到動畫了:

總結

終於完成了這 30 天的挑戰,這 30 天完成了兩個 App,並且做了很多有趣的功能,也使用了一些想嘗試的技術,但這兩個 App 後續還有一些部分可以再做的更好,也可以發布到 App Store 和 Google Play 上,之後會繼續完成這些部分,有興趣的也可以繼續關注我的部落格,謝謝大家!

附上完整專案


上一篇
Day 29 - 顯示指定城市的天氣資訊
系列文
掌握 React Native 與 Expo:30天雙打,新手也能精通跨平台開發!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
hannnahTW
iT邦新手 3 級 ‧ 2023-10-15 09:43:53

恭喜完賽 🎉

我要留言

立即登入留言